<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/11/2
 * Time: 9:38
 */

namespace app\admin\controller;


use app\admin\model\ApiResponse;
use app\admin\lib\AdminController;
use app\common\model\sale\Gifts;
use app\common\model\Sales;

class Sale extends AdminController
{
    /**
     * @return mixed
     */
    public function list() {
        $form = $this->getAndCheckForm([
            ['rows', 'integer',],
            ['page', 'integer',],
            ['type', 'integer',],
        ]);

        $result = Sales::manageList(intval($form['page']??1), intval($form['rows']??10), intval($form['type']));
        var_dump(111111);exit;
        return ApiResponse::success($result);
    }

    public function save() {
        $form = $this->getAndCheckForm([
            ['sales_title', 'require',],
            ['sales_type', 'require|integer',],
            ['sales_start_time', 'integer',],
            ['sales_end_time', 'integer',],
            ['sales_discount', 'float',],
            ['sales_amount', 'float',],
            ['disabled', 'integer',],
            ['gifts', 'array',],
        ]);
        $gifts = $form['gifts'] ?? null;
        $id = $form['sales_id'] ?? 0;
        unset($form['gifts'],$form['sales_id']);

        if (isset($form['sales_discount'])) $form['sales_discount'] = round($form['sales_discount'],2);
        if (isset($form['sales_amount'])) $form['sales_amount'] = round($form['sales_amount'],2);

        if ($id > 0) $sales = Sales::get($id);
        if (empty($sales)) {
            $sales = new Sales();
        }
        $sales->data($form);
        if (!empty($gifts) && is_array($gifts)) {
            $sales->gifts = new Gifts($gifts);
        }

        $sales->save();

        return ApiResponse::success();
    }

    public function disable() {
        $form = $this->getAndCheckForm([
            ['id','require|integer',],
            ['disabled','require|integer',],
        ]);

        $n = Sales::setDisable($form['id'], (1 == $form['disabled'] ? 1 : 0));

        return ApiResponse::success($n);
    }

    /**
     * @return ApiResponse
     */
    public function list_available() {
        return ApiResponse::success(Sales::listAvailable());
    }

}